import { Injectable, OnModuleInit } from '@nestjs/common';
import { MessageService } from '../message/message.service';
import { DeviceService } from '../device/device.service';
import * as net from 'net';

@Injectable()
export class TcpService implements OnModuleInit {
  constructor(
    private readonly messageService: MessageService,
    private readonly deviceService: DeviceService,
  ) {}

  onModuleInit() {
    const server = net.createServer((socket) => {
      socket.on('data', (data) => {
        void (async () => {
          // 打印原始 Buffer
          console.log('收到原始数据:', data);

          // 打印十六进制字符串
          const hexString = data.toString('hex').toUpperCase();
          console.log('收到十六进制数据:', hexString);

          // 解析报文
          const parsed = this.parseData(hexString) as {
            hostAddress?: string;
            reportType?: string;
            hardwareVersion?: string;
            softwareVersion?: string;
            timestamp?: string;
            imei?: string;
            dataType?: string;
          } | null;
          if (!parsed) return;
          // 设备 upsert（有则更新，无则插入）
          try {
            await this.deviceService.updateOrCreate({
              deviceAddress: parsed.hostAddress ?? '',
              deviceType: parsed.reportType ?? '',
              hardwareVersion: parsed.hardwareVersion ?? '',
              softwareVersion: parsed.softwareVersion ?? '',
              lastReportTime: parsed.timestamp ?? '',
              remark: '',
            });

            await this.messageService.create({
              imei: parsed.imei ?? '',
              deviceAddress: parsed.hostAddress ?? '',
              dataType: parsed.dataType ?? '',
              reportType: parsed.reportType || '',
              timestamp: this.messageService.formatTimestamp(
                new Date(parseInt(hexString.slice(20, 28), 16) * 1000),
              ),
              rawData: hexString,
              parsedData: JSON.stringify(parsed),
            });
          } catch (error) {
            console.error('Error saving data:', error);
          }
        })();
      });
    });

    server.listen(10001, '0.0.0.0', () => {
      console.log('TCP服务器已启动在端口10001');
    });
  }

  parseData(hexString: string): any {
    try {
      console.log('开始解析数据:', hexString);

      if (hexString.length < 32) {
        console.log('数据长度不足');
        return null;
      }

      const frameHeader = hexString.slice(0, 8);
      const hostAddress = parseInt(hexString.slice(8, 12), 16);
      const reportTypeHex = hexString.slice(12, 14);
      const reportType = reportTypeHex;
      const dataType = parseInt(hexString.slice(14, 16), 16);
      const dataSequence = hexString.slice(16, 20);
      const timestamp = new Date(parseInt(hexString.slice(20, 28), 16) * 1000);
      const dataLength = parseInt(hexString.slice(28, 32), 16);
      const version = hexString.slice(32, 34);

      // 主机数据专属字段 (reportType = '01')
      if (reportTypeHex === '01') {
        console.log(
          `主机数据长度检查: 实际长度=${hexString.length}, 期望长度>=116`,
        );
        if (hexString.length < 116) {
          console.log('主机数据长度不足');
          return null;
        }

        // 按照正确规则解析主机数据
        const reserved = hexString.slice(34, 36); // 水浸触发次数(调试使用)
        const hostBattery = (
          parseInt(hexString.slice(36, 40), 16) / 100
        ).toFixed(2); // 电池电压: 7.17V
        const currentWaterLeak = parseInt(hexString.slice(40, 42), 16); // 水浸当前状态: 1-有水，2-无水
        const previousWaterLeak = parseInt(hexString.slice(42, 44), 16); // 水浸上一状态: 1-有水，2-无水
        const ambientTemperature = (
          parseInt(hexString.slice(44, 48), 16) / 10
        ).toFixed(1); // 环境温度: 17.0℃
        const ambientTemperatureStatus = parseInt(hexString.slice(48, 50), 16); // 环境温度状态字: 1-越限，2-正常
        const signalStrength = parseInt(hexString.slice(50, 54), 16); // 信号强度: 0x0019 -> 25
        const imei = hexString.slice(54, 84); // IMEI: 30字节
        const imsi = hexString.slice(84, 114); // IMSI: 30字节
        const frameTail = hexString.slice(114, 116); // 校验和
        return {
          frameHeader,
          hostAddress,
          reportType,
          dataType,
          dataSequence,
          timestamp,
          dataLength,
          version,
          reserved,
          hostBattery: hostBattery,
          currentWaterLeak: currentWaterLeak,
          previousWaterLeak: previousWaterLeak,
          ambientTemperature: ambientTemperature,
          ambientTemperatureStatus,
          signalStrength,
          imei,
          imsi,
          frameTail,
        };
      }

      // 测温传感器数据专属字段 (reportType = '02')
      if (reportTypeHex === '02') {
        console.log(
          `测温传感器数据长度检查: 实际长度=${hexString.length}, 期望长度>=326`,
        );
        if (hexString.length < 326) {
          console.log('测温传感器数据长度不足');
          return null;
        }

        // 按照正确规则解析测温传感器数据
        const reserved = hexString.slice(34, 36); // 水浸触发次数
        const sensorFrameHeader = hexString.slice(36, 44); // 局放测温传感器数据的帧头: 444C4A43
        const sensorAddress = hexString.slice(44, 46); // 局放测温传感器地址
        const sensorDataType = parseInt(hexString.slice(46, 48), 16); // 局放测温传感器数据类型
        const sensorDataSequence = hexString.slice(48, 52); // 局放测温传感器数据序号
        const sensorDataLength = parseInt(hexString.slice(52, 56), 16); // 局放测温传感器有效数据字节
        const sensorVersion = hexString.slice(56, 58); // 局放测温传感器软硬件版本
        const sensorReserved = hexString.slice(58, 60); // 预留

        // 局放峰值和均值数据 (12组)
        const partialDischargeData: {
          max: number;
          avg: number;
        }[] = [];
        for (let i = 60; i < 108; i += 4) {
          const tempStr = hexString.slice(i, i + 4);
          partialDischargeData.push({
            max: parseInt(tempStr.slice(0, 2), 16),
            avg: parseInt(tempStr.slice(2, 4), 16),
          });
        }

        // 状态字
        const partialDischargeStatus = parseInt(hexString.slice(108, 110), 16); // 局放状态字: 1-关注，2-正常
        const temperatureMutationStatus = parseInt(
          hexString.slice(110, 112),
          16,
        ); // 电缆温度突变状态字: 1-关注，2-正常
        const temperatureLimitStatus = parseInt(hexString.slice(112, 114), 16); // 电缆温度越限状态字: 1-关注，2-正常
        const reserved2 = hexString.slice(114, 116); // 预留

        // 电缆温度值
        const cableTemperature = parseInt(hexString.slice(116, 120), 16) / 10;
        const cableTemperatureReserved = hexString.slice(120, 124); // 预留

        // 60组温度值 (每组4字节，前2字节代表电缆温度值，后2字节预留)
        const temperatureGroups: Array<{
          temperature: number | null;
        }> = [];
        for (let i = 124; i < 587; i += 4) {
          const tempValue = hexString.slice(i, i + 4);
          temperatureGroups.push({
            temperature:
              tempValue === '7FFF' ? null : parseInt(tempValue, 16) / 10,
          });
        }

        const checksum = hexString.slice(587, 589); // 校验和
        const frameTail = hexString.slice(589, 591); // 帧尾
        return {
          frameHeader,
          hostAddress,
          reportType,
          dataType,
          dataSequence,
          timestamp,
          dataLength,
          version,
          reserved,
          sensorFrameHeader,
          sensorAddress,
          sensorDataType,
          sensorDataSequence,
          sensorDataLength,
          sensorVersion,
          sensorReserved,
          partialDischargeData,
          partialDischargeStatus,
          temperatureMutationStatus,
          temperatureLimitStatus,
          reserved2,
          cableTemperature,
          cableTemperatureReserved,
          temperatureGroups,
          checksum,
          frameTail,
        };
      }
      return null;
    } catch (error) {
      console.error('解析数据失败:', error);
      return null;
    }
  }
}
